package com.file.system.plugin.mybatis_plus;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.querys.MySqlQuery;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;

import java.util.*;

// 演示例子，执行 main 方法控制台输入模块表名回车自动生成对应项目目录中
public class CodeGenerator {
    private static final String pkgName = "business";

    /**
     * <p>
     * 读取控制台内容
     * </p>
     */
    public static String scanner(String tip) {
        Scanner scanner = new Scanner(System.in);
        StringBuilder help = new StringBuilder();
        help.append("输入" + tip + "：");
        System.out.println(help.toString());
        if (scanner.hasNext()) {
            String ipt = scanner.next();
            if (StringUtils.isNotBlank(ipt)) {
                return ipt;
            }
        }
        throw new MybatisPlusException("输入正确的" + tip + "！");
    }

    public static void main(String[] args) {
        String controllerName = scanner("注释");
        String tableName = scanner("表名");
        // 代码生成器
        AutoGenerator mpg = new AutoGenerator();

        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        String projectPath = System.getProperty("user.dir");
        gc.setOutputDir(projectPath + "/src/main/java");
        gc.setAuthor(scanner("姓名"));
        gc.setOpen(false);
        gc.setFileOverride(true);//覆盖文件（true-替换；false-不存在 重新生成，存在 不改变原有代码）
        // gc.setSwagger2(true); 实体属性 Swagger2 注解
        mpg.setGlobalConfig(gc);

        gc.setBaseColumnList(true);
        gc.setBaseResultMap(true);


        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig().setDbQuery(new MySqlQuery() {
            @Override
            public String tableFieldsSql() {
                String sql = "SELECT " +
                        "a.column_name AS column_name, " +
                        "a.column_name AS Field, " +
                        "NULL AS Extra, " +
                        "a.column_type AS type, " +
                        "a.column_comment AS COMMENT, " +
                        "a.column_comment AS comments, " +
                        "a.data_type, " +
                        "IF" +
                        "( a.NUMERIC_PRECISION IS NULL, CAST( a.CHARACTER_MAXIMUM_LENGTH AS CHAR ), a.NUMERIC_PRECISION ) AS length, " +
                        "a.COLUMN_KEY AS 'key', " +
                        "b.ENGINE  as 'engine' " +
                        "FROM " +
                        "INFORMATION_SCHEMA.COLUMNS AS a, " +
                        "information_schema.TABLES AS b " +
                        "WHERE " +
                        "a.table_name = '" + tableName + "' " +
                        "AND a.table_schema = 'hus_sign' " +     //库名
                        "AND b.table_name = '" + tableName + "' " +
                        "AND b.table_schema = 'hus_sign'";       //库名

                System.out.println(sql);
                return sql;
            }

            @Override
            public String[] fieldCustom() {
                return new String[]{"length", "data_type", "engine"};
            }
        });
        //连接串
        dsc.setUrl("jdbc:mysql://192.168.0.100:3306/hus_sign?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8");
        // dsc.setSchemaName("public");
        dsc.setDriverName("com.mysql.cj.jdbc.Driver");
        dsc.setUsername("root");
        dsc.setPassword("Mmysql809");
        mpg.setDataSource(dsc);


        // 包配置
        PackageConfig pc = new PackageConfig();
//        pc.setModuleName(scanner("模块名"));
        pc.setParent("com.file.system");
        if (StrUtil.isNotEmpty(pkgName)) {

            pc.setController("controller." + pkgName);
            pc.setMapper("mapper." + pkgName);
            pc.setEntity("entity." + pkgName);
            pc.setService("service." + pkgName);
            pc.setServiceImpl("service.impl." + pkgName);
        }


        mpg.setPackageInfo(pc);


        // 自定义配置
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {

                Map<String, Object> map = new HashMap<>();
                String controllerPath = "/" + tableName.replaceAll("_", "/");
                map.put("controllerName", controllerName);
                map.put("controllerPath", controllerPath);
                this.setMap(map);
            }
        };

        mpg.setCfg(cfg);

        // 如果模板引擎是 freemarker
        String templatePath = "/templates/mapper.xml.ftl";


        // 自定义输出配置
        List<FileOutConfig> focList = new ArrayList<>();
        // 自定义配置会被优先输出
        focList.add(new FileOutConfig(templatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {

                String xmlPath = "";
                if (StrUtil.isNotEmpty(pkgName)) {
                    xmlPath = projectPath + "/src/main/resources/mapper/" + pkgName + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
                } else {
                    xmlPath = projectPath + "/src/main/resources/mapper/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
                }
                // 自定义输出文件名 ， 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化！！
                return xmlPath;
            }
        });

        cfg.setFileOutConfigList(focList);


        // 配置模板
        TemplateConfig templateConfig = new TemplateConfig();

        // 配置自定义输出模板
        templateConfig.setXml(null);
        mpg.setTemplate(templateConfig);

        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        strategy.setSuperEntityClass("com.file.system.entity.basic.WebBasic");
        strategy.setEntityLombokModel(true);
        strategy.setRestControllerStyle(true);
        // 公共父类
//        strategy.setSuperControllerClass(null);
        // 写于父类中的公共字段
        strategy.setSuperEntityColumns("create_time", "create_by", "create_name", "delete_time", "delete_by", "delete_name", "update_time", "update_by", "update_name", "is_del");
        strategy.setInclude(tableName);
        strategy.setControllerMappingHyphenStyle(true);
        strategy.setTablePrefix(pc.getModuleName() + "_");
        strategy.setEntityTableFieldAnnotationEnable(false);


        mpg.setCfg(cfg);
        mpg.setStrategy(strategy);
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        mpg.execute();
    }

}